<?php
function _tranxuantuan_ketqua() {
	$form_ketqua = drupal_get_form('_tranxuantuan_form_ketqua_form');
	return drupal_render($form_ketqua);	
}
function _tranxuantuan_form_ketqua_form($form, &$form_state) {
	$files_dir = variable_get('file_public_path', conf_path() . '/files/kq');
	//dpm($files_dir);
	$arr = glob($files_dir .'/*.txt',GLOB_BRACE);
	//dpm($arr);
 	$form['selected'] = array(
    '#type' => 'select',
    '#title' => t('Chọn file Chấm điểm'),
		'#options' => $arr,
	); 
 	$form['ky_thi'] = array(
    '#type' => 'textfield',
    '#title' => t('Kỳ thi'),
		'#required' => TRUE,
	); 
	
	$form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Chấm điểm'),			
  );
	return $form;
}
function _tranxuantuan_form_ketqua_form_submit($form, &$form_state) {
	$files_dir = variable_get('file_public_path', conf_path() . '/files/kq');
	$arr = glob($files_dir .'/*.txt',GLOB_BRACE);
	$i = $form_state['values']['selected'];
	$kythi = $form_state['values']['ky_thi'];
	$filepath = $arr[$i];
	//dpm($filepath);
	xulyketqua($filepath, $kythi);
}
function xulyketqua($filepath, $kythi) {
	$module_path = drupal_get_path('module', 'tranxuantuan');
	$dir    = $module_path .'/da';

	if (!file_exists($filepath)) return null;
	$content = trim(file_get_contents($filepath));
	$lines = explode("\n", $content);
	$data = array();
	foreach($lines as $num=>$line) {
		$mssv = substr($line, 0, 5);
		//dpm ($mssv);		
		$made = substr($line, 5, 3);
		//dpm($made);
		$t = $dir. '/' .$made .'.json';
		//dpm($t);
		$file = trim(file_get_contents($t));
		$file2 = unserialize($file);
		//dpm($file2);
		$dapan_str = substr($line, 8, -1);
		//dpm($dapan_str);
		$dapan = array();
		$diem = 0;
		$da2 = '';
		for($i=0;$i<strlen($dapan_str);$i++) {
			if( $dapan_str[$i] == $file2[$i]['dap_an'] ) {
			$diem += $file2[$i]['thang_diem'];
			}
			if( $dapan_str[$i] == '*' ) {
			$da2 .= $i .',';
			}
		}
		//dpm($diem);
	$node = new stdClass();// creat a new node object
	$node->type = "ket_qua";
	$node->title = $mssv;
	$node->language = 'en';
	$node->field_kq_made['und'][0]['value'] = $made;
	$node->field_kq_diem['und'][0]['value'] = $diem;
	$node->field_kq_kythi['und'][0]['value'] = $kythi;	
	$node->field_kq_2da['und'][0]['value'] = $da2;
	$node = node_submit($node);
	node_save($node);
	}
	drupal_set_message(t('Chấm điểm thành công ! '));
	
}